package test;

import way.learning.zz.DirectoryPoller;
import way.learning.zz.source.FtpDirectory;
import way.learning.zz.source.PolledDirectory;
import org.apache.commons.net.ftp.FTPFile;

import java.util.List;
import java.util.concurrent.TimeUnit;


public class FtpMonitor {

    private String workingDirectory;
    private String host;
    private int port;
    private String username;
    private String pwd;

    //构造函数
    public FtpMonitor(String dir, String host, int port, String username, String pwd){
        this.workingDirectory = dir;
        this.host = host;
        this.port = port;
        this.username = username;
        this.pwd = pwd;
    }

    //开始进行监测，按interval为时间间隔不断轮询
    public List<FTPFile> beginMonitor(int interval){

        try {
            /**
             * polledDirectory接口的实现表示轮询文件元素的目录。
             */
            PolledDirectory polledDirectory = new FtpDirectory(host, port, workingDirectory, username, pwd);


            MyListener listener = new MyListener();
            /**
             * 一旦建立了DirectoryPoller，它可以用来添加额外的轮询目录，或者删除轮询的目录，添加额外的侦听器，或删除侦听器。
             * DirectoryPoller用于添加/删除/终止轮询机制
             */
            DirectoryPoller dp = DirectoryPoller.newBuilder()
                    //将给定目录添加到轮询目录列表中，必须至少添加一个目录
                    .addPolledDirectory(polledDirectory)

                    //将给定的侦听器添加到接收通知的Rdp4jListener列表中
                    .addListener(listener)

                    //设置每个轮询周期之间的间隔。 可选参数。默认值为1000毫秒。
                    .setPollingInterval(interval, TimeUnit.SECONDS)

                    //构建一个DirectoryPoller实例，启动轮询循环机制
                    .start();


            System.out.println("从listener获取到的filename" + listener.getNewFileName());



            TimeUnit.HOURS.sleep(2);

            dp.stop();
        }catch(InterruptedException e){
            e.printStackTrace();
        }

        return null;
    }


    public static void main(String[] args) throws Exception {

        String host = "119.23.14.212";
        int port = 21001;
        String username = "ndycfd2";
        String password = "1Q3qKcr";
        String workingDirectory = "/";

        //单位秒
        int interval = 5;


        FtpMonitor ftpMonitor = new FtpMonitor(workingDirectory, host, port, username, password);
        ftpMonitor.beginMonitor(interval);


    }
}
